/*
 *  Copyright (C) 2010 Francesco Boffa (aka AlfaOmega08)
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package Engine;

import ImageFormats.*;
import java.io.*;

public class Ps1 {
	ImageFormat Image;

	SystemCnf SysCnf = new SystemCnf();
	CpuInterpreter Cpu;
	Memory Mem = new Memory();

	public void Init(ImageFormat i) throws Exception {
		Image = i;

		LoadBios();

		SysCnf.LoadFromImage(Image);
		Executable e = new Executable(Image, SysCnf.getExecutablePath());
		Cpu = new CpuInterpreter(e, Mem);
	}

	private void LoadBios() throws Exception {
		int len = 0;
		DataInputStream r = null;
		try {
			len = (int) new File(Engine.Config.getConfig("BiosPath")).length();
			r = new DataInputStream(new FileInputStream(Engine.Config.getConfig("BiosPath")));
		} catch (FileNotFoundException e) {
			System.out.println("The BIOS Image File was not found. Set it in the preferences or do not use the PS1 BIOS " + e.getMessage());
			System.exit(-1);
		}

		if (len != 0x80000)
			System.out.println("Bios size != 512 Kb");

		for (int i = 0; i < 0x80000; i++) {
			Mem.getRomMemory()[i] = (byte) r.readByte();
		}

		Cpu = new CpuInterpreter(0xBFC00000, 0, 0, Mem);
		while (Cpu.Pc != 0x80030000) {
			Cpu.ExecuteBlock();
		}
	}

	public void Start() throws Exception {
		Cpu.Execute();
	}
}
